﻿using Candy.Infrastructure;
using Candy.Model;
using Candy.Web.Data;
using GalaSoft.MvvmLight.Threading;
using System;
using System.Collections.ObjectModel;
using System.Linq;

namespace Candy.ViewModel
{
    public class GenotypesViewModel : CandyViewModelBase
    {
        private ObservableCollection<GenotypeEditViewModel> _genotypesVms;
        public ObservableCollection<GenotypeEditViewModel> GenotypeVms
        {
            get
            {
                return _genotypesVms;
            }
            set
            {
                _genotypesVms = value;
                RaisePropertyChanged("GenotypeVms");
            }
        }

        private ObservableCollection<GenotypeDto> _genotypes;
        public ObservableCollection<GenotypeDto> Genotypes
        {
            get
            {
                return _genotypes;
            }
            set
            {
                _genotypes = value;
                RaisePropertyChanged("Genotypes");
            }
        }




        IDataService _dataService;
        INavigationService _navigationService;
        public GenotypesViewModel(IDataService dataService, INavigationService navigationService)
        {
            _dataService = dataService;
            _navigationService = navigationService;

            _dataService.ProjectInitialized += _dataService_ProjectInitialized;
 
        }

        void Genotypes_EntityRemoved(object sender, System.ServiceModel.DomainServices.Client.EntityCollectionChangedEventArgs<GenotypeDto> e)
        {
            DispatcherHelper.CheckBeginInvokeOnUI(() =>
                {
                    _genotypes.Remove(e.Entity);
                    var toRem = _genotypesVms.SingleOrDefault(x => x.Entity.Id == e.Entity.Id);
                    if (toRem != null)
                        _genotypesVms.Remove(toRem);
                });
        }

        void Genotypes_EntityAdded(object sender, System.ServiceModel.DomainServices.Client.EntityCollectionChangedEventArgs<GenotypeDto> e)
        {
            DispatcherHelper.CheckBeginInvokeOnUI(() =>
          {
              _genotypes.Add(e.Entity);
              var toAdd = new GenotypeEditViewModel(_dataService, _navigationService, e.Entity);
              _genotypesVms.Add(toAdd);
          });
        }

        void _dataService_ProjectInitialized(object sender, EventArgs e)
        {
            GenotypeVms = new ObservableCollection<GenotypeEditViewModel>(_dataService.Genotypes.OrderBy(x => x.Name).Select(x => new GenotypeEditViewModel(_dataService, _navigationService, x)));
            Genotypes = new ObservableCollection<GenotypeDto>(_dataService.Genotypes.OrderBy(x => x.Name));
            _dataService.Genotypes.EntityAdded += Genotypes_EntityAdded;
            _dataService.Genotypes.EntityRemoved += Genotypes_EntityRemoved;
        }

    }
}
